package admin_service

import (
	"shop/common/log"
	"shop/dao"
	"shop/entity"
	"shop/utils/genutil"
	"shop/utils/result"
	"shop/utils/sessionutil"
)

// 个人中心

type UpdatePasswordParams struct {
	OldPassword string `json:"oldPassword"`
	NewPassword string `json:"newPassword"`
}

func UpdatePassword(userId int64, params *UpdatePasswordParams) *result.Result {
	user := &entity.SysUser{}
	tx := dao.GetTx().Model(user).Where("id", userId).Take(user)
	if user.Id == 0 {
		return result.Fail("用户不存在")
	}
	encryptPassword := genutil.Md5HexWithSalt(params.OldPassword, user.Salt)
	if encryptPassword != user.Password {
		return result.Fail("旧密码错误")
	}

	tx.Model(user).Where("id", userId).UpdateColumn("password", genutil.Md5HexWithSalt(params.NewPassword, user.Salt))
	return result.Ok(tx.Commit().RowsAffected)
}

// UpdateUserAvatar 更新个人头像
func UpdateUserAvatar(userId int64, url string) *result.Result {
	err := dao.GetDB().Table(entity.TableNameSysUser).Where("id", userId).UpdateColumn("avatar", url).Error
	if err != nil {
		log.Errorf("更新数据库失败，err: %v", err)
		return result.Fail("头像更新失败")
	}
	// 更新缓存
	user := sessionutil.GetSysUserInfo(userId)
	user.Avatar = url
	sessionutil.SetSysUserCache(user)
	return result.Ok(url)
}
